package com.example.onlinemusic.Controller;

import com.example.onlinemusic.mapper.UserMapper;
import com.example.onlinemusic.model.User;
import com.example.onlinemusic.tools.Constant;
import com.example.onlinemusic.tools.ResponseBodyMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserMapper userMapper;
    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    //BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
    @RequestMapping("/login")
    public ResponseBodyMessage<User> login(@RequestParam String username, @RequestParam String password, HttpServletRequest request){
//        User userLogin = new User();
//        userLogin.setUsername(username);
//        userLogin.setPassword(password);

        User user = userMapper.selectByName(username);
        log.info("user:{}",user);

        if(user == null){
            return new ResponseBodyMessage<>(-1,"失败",user);
        }
        boolean flg = bCryptPasswordEncoder.matches(password, user.getPassword());
        if(!flg){
            return new ResponseBodyMessage<>(-1,"用户名或密码错误",user);
        }
        request.getSession().setAttribute(Constant.USERINFO_SESSION_KEY,user);
        return new ResponseBodyMessage<>(200,"成功",user);
    }
//    public static void main(String[] args) {
//        String password = "123456";
//        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
//        String newPassword = bCryptPasswordEncoder.encode(password);
//        System.out.println("加密的密码为: "+newPassword);
//        boolean same_password_result = bCryptPasswordEncoder.matches(password,newPassword);
//        System.out.println("加密的密码和正确密码对比结果: "+same_password_result);
//        boolean other_password_result = bCryptPasswordEncoder.matches("987654",newPassword);
//        System.out.println("加密的密码和错误的密码对比结果: " + other_password_result);
//    }
}
